// Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.

// 清理数据库数据
package clean

import (
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/config"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/models"
	app_process "codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/models/appprocess"
	client_session "codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/models/clientsession"
	server_session "codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/models/serversession"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/log"
	"time"
)

const (
	DataBaseInitTime = 60
)

// Init 用于定期删除数据库中数据
func Init() {
	if config.GlobalConfig.CleanStrategy == "on" || config.GlobalConfig.CleanStrategy == "ON" {
		go InitDataBase(DataBaseInitTime * time.Second)
	}
}

func InitDataBase(t time.Duration) {
	appProcessBackupDao := app_process.NewAppProcessBackupDao(models.MySqlOrm)
	serverSessionBackupDao := server_session.NewServerSessionBackupDao(models.MySqlOrm)
	clientSessionBackupDao := client_session.NewClientSessionBackupDao(models.MySqlOrm)
	ticker := time.Tick(t)
	for i := range ticker {
		log.RunLogger.Infof("[%sexpress data cleaner] start backup and clean express data", i.Local())
		// App process backup
		go func() {
			err := appProcessBackupDao.CleanAppProcessBackup(config.GlobalConfig.CleanupDays)
			if err != nil {
				log.RunLogger.Errorf("[express data cleaner] clear express app process from backup table error for %v", err)
			}
		}()
		go func() {
			err := appProcessBackupDao.BackupAppProcess(config.GlobalConfig.BackupDays)
			if err != nil {
				log.RunLogger.Errorf("[express data cleaner] backup express app process from runtime error for %v", err)
			}
		}()
		// Server session backup
		go func() {
			err := serverSessionBackupDao.CleanServerSessionBackup(config.GlobalConfig.CleanupDays)
			if err != nil {
				log.RunLogger.Errorf("[express data cleaner] clear express server session from backup table error for %v", err)
			}
		}()
		go func() {
			err := serverSessionBackupDao.BackupServerSession(config.GlobalConfig.BackupDays)
			if err != nil {
				log.RunLogger.Errorf("[express data cleaner] backup express server session from runtime error for %v", err)
			}
		}()
		// Client session backup
		go func() {
			err := clientSessionBackupDao.CleanClientSessionBackup(config.GlobalConfig.CleanupDays)
			if err != nil {
				log.RunLogger.Errorf("[express data cleaner] clear express client session from backup table error for %v", err)
			}
		}()
		go func() {
			err := clientSessionBackupDao.BackupClientSession(config.GlobalConfig.BackupDays)
			if err != nil {
				log.RunLogger.Errorf("[express data cleaner] backup express client session from runtime error for %v", err)
			}
		}()
	}
}
